import { defineStore } from "pinia";
import {
  type userType,
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import { getToken, type GetTokenResult, getUserinfo } from "@/api/login";
import { type RefreshTokenResult, refreshTokenApi } from "@/api/user";
import { useMultiTagsStoreHook } from "./multiTags";
import {
  type DataInfo,
  setToken,
  removeToken,
  userKey,
  setuserInfo,
  type TokenInfo,
  TokenKey
} from "@/utils/auth";

export const useUserStore = defineStore({
  id: "pure-user",
  state: (): {
    permissions: any[];
    user: object;
    access_token: string;
    refresh_token: string;
    expires_in: number;
  } => ({
    // 页面级别权限
    user: storageLocal().getItem<DataInfo>(userKey)?.user ?? {},
    // 按钮级别权限
    permissions: storageLocal().getItem<DataInfo>(userKey)?.permissions ?? [],
    access_token:
      storageLocal().getItem<TokenInfo>(TokenKey)?.access_token ?? "",
    refresh_token:
      storageLocal().getItem<TokenInfo>(TokenKey)?.refresh_token ?? "",
    expires_in: storageLocal().getItem<TokenInfo>(TokenKey)?.expires_in ?? 0
  }),
  actions: {
    /** 存储按钮级别权限 */
    SET_PERMS(permissions: Array<string>) {
      this.permissions = permissions;
    },
    /** 存储按钮级别权限 */
    SET_USER(user: object) {
      this.user = user;
    },
    SET_ACCESS_TOKEN(access_token: string) {
      this.access_token = access_token;
    },
    SET_REFRESH_TOKEN(refresh_token: string) {
      this.refresh_token = refresh_token;
    },
    SET_EXPIRES_IN(expires_in: number) {
      this.expires_in = expires_in;
    },

    /** 登入 */
    async loginByUsername(data: object) {
      return new Promise<GetTokenResult>((resolve, reject) => {
        getToken(data)
          .then(async res => {
            setToken(res);
            const { access_token } = res;
            await getUserinfo({ access_token }).then(resUserIndo => {
              setuserInfo(resUserIndo);
            });
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      this.permissions = [];
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login").then(() => {
        this.SET_USER({});
        this.SET_PERMS([]);
        this.SET_ACCESS_TOKEN("");
        this.SET_REFRESH_TOKEN("");
        this.SET_EXPIRES_IN(0);
      });
    },
    /** 刷新`token` */
    async handRefreshToken(data) {
      return new Promise<RefreshTokenResult>((resolve, reject) => {
        refreshTokenApi(data)
          .then(data => {
            if (data) {
              setToken(data.data);
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
